import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:video_player/video_player.dart';
import 'package:yp/config/config.dart';
import 'package:yp/pages/mall_app/commodity_search/shop_search/logic.dart';
import 'package:yp/pages/mall_app/commodity_search/shop_search/state.dart';
import 'package:yp/services/api.dart';
import 'package:yp/utils/videoplayer/video_player_plus.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../../helper.dart';
import '../../../../router.dart';

class ShopSearchPage extends StatefulWidget {
  ShopSearchPage({Key key}) : super(key: key);

  @override
  _ShopSearchPageState createState() => _ShopSearchPageState();
}

class _ShopSearchPageState extends State<ShopSearchPage> {
  final ShopSearchLogic logic = Get.put(ShopSearchLogic());
  final ShopSearchState state = Get.find<ShopSearchLogic>().state;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xffF7F7F7),
      appBar: AppBar(
        centerTitle: true,
        elevation: 0,
        backgroundColor: Color(0xffEA5504),
        title: Text(
          '店铺搜索',
          style: TextStyle(
            color: Colors.white,
            fontSize: 17,
          ),
        ),
        iconTheme: IconThemeData(
          color: Colors.white, //修改颜色
        ),
      ),
      body: GetBuilder<ShopSearchLogic>(builder: (logic) {
        return Container(
          color: Color(0xffF7F7F7),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                color: Colors.white,
                child: Row(
                  children: [
                    Expanded(
                      child: Container(
                        height: 30,
                        margin:
                            EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                        decoration: BoxDecoration(
                            color: Color(0xffF7F7F7),
                            borderRadius: BorderRadius.circular(20)),
                        child: TextField(
                          controller: logic.state.searchTextEditingController,
                          maxLines: 1,
                          style: TextStyle(
                            color: Color(0xff222222),
                            fontSize: 14,
                          ),
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            contentPadding: EdgeInsets.all(0),
                            hintText: '请输入店内商品名称',
                            hintStyle: TextStyle(
                              color: Color(0xffcccccc),
                              fontSize: 14,
                            ),
                            enabledBorder: OutlineInputBorder(
                              // 设置输入框可编辑时的边框样式
                              borderRadius: BorderRadius.all(
                                  Radius.circular(90)), // 设置边框四个角的弧度
                              borderSide: BorderSide(
                                // 用来配置边框的样式
                                color: Color(0xffEA5504),
                                width: setWidth(2), // 设置边框的粗细
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                              // 用来配置输入框获取焦点时的颜色
                              borderRadius: BorderRadius.all(
                                  Radius.circular(90)), // 设置边框四个角的弧度
                              borderSide: BorderSide(
                                // 用来配置边框的样式
                                color: Colors.transparent, //设置边框的颜色
                                width: setWidth(2), // 设置边框的粗细
                              ),
                            ),
                            prefixIcon: InkWell(
                              onTap: () {},
                              child: Container(
                                width: 15,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(setWidth(28)),
                                    bottomLeft: Radius.circular(setWidth(28)),
                                  ),
                                ),
                                alignment: Alignment.center,
                                child: Icon(
                                  Icons.search,
                                  color: Color(0xffcccccc),
                                  size: 20,
                                ),
                              ),
                            ),
                          ),
                          onSubmitted: (value) {
                            // if (value.trim().isEmpty) {
                            //   toast('关键字不能为空');
                            //   return;
                            // }
                            state.currentPage = 1;
                            logic.onReady();
                          },
                        ),
                      ),
                    ),
                    Container(
                      child: TextButton(
                        child: Text(
                          "取消",
                          style: TextStyle(color: Color(0xff222222)),
                        ),
                        onPressed: () => Get.back(result: () {}),
                      ),
                    )
                  ],
                ),
              ),
              Expanded(
                  child: state.shopInfoList.length > 0
                      ? SingleChildScrollView(
                          child: Column(
                            children: List.generate(
                              state.shopInfoList.length,
                              (index) => Container(
                                color: const Color(0xffffffff),
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 10, vertical: 10),
                                child: InkWell(
                                  onTap: () {
                                    logic.getAndGoThirdShop(state
                                        .shopInfoList[index]['ec_shop_num_id']);
                                  },
                                  child: Row(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Container(
                                        margin:
                                            const EdgeInsets.only(right: 10),
                                        color: const Color(0xfff4f4f4),
                                        width: setWidth(100),
                                        height: setWidth(100),
                                        alignment: Alignment.center,
                                        child: Image.network(
                                            state.shopInfoList[index]
                                                            ['ec_shop_logo'] ==
                                                        null ||
                                                    state.shopInfoList[index]
                                                            ['ec_shop_logo'] ==
                                                        ''
                                                ? Config.orderEmpty
                                                : state.shopInfoList[index]
                                                    ['ec_shop_logo']),
                                        // child: Text(
                                        //   '暂无\n图片',
                                        //   style: TextStyle(
                                        //       color: const Color(0xff999999),
                                        //       fontSize: 12),
                                        // ),
                                      ),
                                      Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Text(
                                            state.shopInfoList[index]
                                                ['ec_shop_name'],
                                            overflow: TextOverflow.ellipsis,
                                            style: TextStyle(
                                              color: const Color(0xff333333),
                                              fontSize: 15,
                                            ),
                                          ),
                                          Text(
                                            '进入店铺',
                                            style: TextStyle(
                                              color: const Color(0xffEA5504),
                                              fontSize: 12,
                                            ),
                                          )
                                        ],
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            )..add(
                                Center(
                                  child: Container(
                                    margin: const EdgeInsets.only(top: 10),
                                    child: Text(
                                      '没有更多了~',
                                      style: TextStyle(
                                          color: const Color(0xff999999)),
                                    ),
                                  ),
                                ),
                              ),
                          ),
                        )
                      : state.recommendCommodityList.length > 0
                          ? _searchResultAndRecommendCommodityList()
                          : SizedBox()),
            ],
          ),
        );
      }),
    );
  }

  //  优惠券类型
  Widget _couponType(String typeIndex) {
    var type = '折扣券';
    if (typeIndex == '0') {
      type = '折扣券';
    } else if (typeIndex == '1') {
      type = '现金券';
    } else if (typeIndex == '2') {
      type = '免邮券';
    } else if (typeIndex == '8') {
      type = '兑换券';
    }

    return Container(
      child: Text(
        type,
        style: TextStyle(
          color: Color(0xffa5673f),
          fontSize: 16,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  List<Widget> _newList(dynamic adList) {
    var commonWidgets = List<Widget>();
    for (var item in adList) {
      if (item['adv_type'] == '1') {
        commonWidgets.add(
          Container(
            margin: EdgeInsets.only(bottom: 20.w),
            child: Stack(
              children: <Widget>[
                new Image(
                  width: 750.r,
                  height: 375.r,
                  fit: BoxFit.fill,
                  image: new NetworkImage(
                    item['adv_object_url'],
                  ),
                ),
                item['tag_name'] != null
                    ? Positioned(
                        //方法二
                        right: 20.w,
                        bottom: 20.w,
                        child: new Container(
                          padding: EdgeInsets.only(
                            left: 6.0,
                            right: 6.0,
                            top: 2.0,
                            bottom: 2.0,
                          ),
                          decoration: BoxDecoration(
                            border: Border.all(
                              width: 1,
                              color: Color(0xff708090),
                            ),
                            borderRadius: BorderRadius.all(
                              Radius.circular(10),
                            ),
                          ),
                          child: Text(
                            item['tag_name'],
                            style: TextStyle(
                              color: Color(0xff708090),
                              fontSize: 10,
                            ),
                          ),
                        ),
                      )
                    : Container(),
              ],
            ),
          ),
        );
      } else if (item['adv_type'] == '2') {
        commonWidgets.add(
          Container(
            margin: EdgeInsets.only(bottom: 20.w),
            child: Stack(
              children: <Widget>[
                new VideoPlayerPlus(
                  VideoPlayerController.network(item['adv_object_url']),
                ),
                item['tag_name'] != null
                    ? Positioned(
                        //方法二
                        right: 20.w,
                        bottom: 20.w,
                        child: new Container(
                          padding: EdgeInsets.only(
                            left: 6.0,
                            right: 6.0,
                            top: 2.0,
                            bottom: 2.0,
                          ),
                          decoration: BoxDecoration(
                            // color: Color(0xff708090),
                            border: Border.all(
                              width: 1,
                              color: Color(0xff708090),
                            ),
                            borderRadius: BorderRadius.all(
                              Radius.circular(10),
                            ),
                          ),
                          child: Text(
                            item['tag_name'],
                            style: TextStyle(
                              color: Color(0xff708090),
                              fontSize: 10,
                            ),
                          ),
                        ),
                      )
                    : Container(),
              ],
            ),
          ),
        );
      } else if (item['adv_type'] == '3') {
        Map<String, dynamic> user = jsonDecode(item['style_num_name']);
        user.forEach((key, value) {
          value[0]['shop_num_id'] = key;
          item['mdms_style'] = value[0];
        });
        commonWidgets.add(
          InkWell(
            onTap: () {
              String itemNumId =
                  item['mdms_style']['default_item_num_id'].toString();
              String styleNumId = item['mdms_style']['style_num_id'].toString();
              String ecStyleNumId =
                  item['mdms_style']['ec_style_num_id'].toString();
              Get.toNamed(RouteConfig.goodsDetail, arguments: {
                'itemNumId': itemNumId,
                'styleNumId': styleNumId,
                'shopId': item['mdms_style']['shop_num_id'],
                'ecStyleNumId': ecStyleNumId,
                'typeIndex': item['mdms_style']['is_pre_sale'] ?? 0,
              });
            },
            child: Container(
              margin: EdgeInsets.only(bottom: 20.w, left: 20.w, right: 20.w),
              padding: EdgeInsets.only(
                  left: 30.w, right: 30.w, top: 25.w, bottom: 15.w),
              decoration: BoxDecoration(
                  boxShadow: [BoxShadow(color: Colors.grey, blurRadius: 5.0.w)],
                  color: Colors.white,
                  borderRadius: new BorderRadius.circular((20.0.w))),
              child: Column(
                children: [
                  // Container(
                  //   alignment: Alignment.centerLeft,
                  //   margin: EdgeInsets.only(right: 10.w, bottom: 30.w),
                  //   child: Text(
                  //     item['mdms_style']['title'],
                  //     style: TextStyle(
                  //       color: Color(0xff333333),
                  //       fontWeight: FontWeight.bold,
                  //       fontSize: 32.w,
                  //     ),
                  //   ),
                  // ),
                  Container(
                    constraints: BoxConstraints(minHeight: 250.w),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          // width: 300.w,
                          child: Image.network(
                            item['mdms_style']['image_default_id'],
                            width: 250.w,
                            height: 220.w,
                            fit: BoxFit.cover,
                          ),
                        ),
                        Expanded(
                          child: Container(
                            margin: EdgeInsets.only(left: 30.w),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Container(
                                  alignment: Alignment.centerLeft,
                                  child: Text(
                                    item['mdms_style']['style_num_name'],
                                    style: TextStyle(
                                      color: Color(0xff666666),
                                      fontWeight: FontWeight.bold,
                                      fontSize: 30.w,
                                    ),
                                  ),
                                ),
                                Stack(
                                  children: [
                                    item['tag_name'] != null
                                        ? Positioned(
                                            //方法二
                                            right: 0,
                                            bottom: 0,
                                            child: new Container(
                                              padding: EdgeInsets.only(
                                                left: 6.0,
                                                right: 6.0,
                                                top: 2.0,
                                                bottom: 2.0,
                                              ),
                                              decoration: BoxDecoration(
                                                // color: Color(0xff708090),
                                                border: Border.all(
                                                  width: 1,
                                                  color: Color(0xff708090),
                                                ),
                                                borderRadius: BorderRadius.all(
                                                  Radius.circular(30),
                                                ),
                                              ),
                                              child: Text(
                                                item['tag_name'],
                                                style: TextStyle(
                                                  color: Color(0xff708090),
                                                  fontSize: 10,
                                                ),
                                              ),
                                            ),
                                          )
                                        : Container(),
                                    Container(
                                      alignment: Alignment.centerLeft,
                                      margin: EdgeInsets.only(top: 80.w),
                                      child: Text(
                                        '¥ ${item['mdms_style']['price']}',
                                        style: TextStyle(
                                          color: Color(0xff666666),
                                          fontWeight: FontWeight.bold,
                                          fontSize: 30.w,
                                        ),
                                      ),
                                    ),
                                  ],
                                )
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      } else if (item['adv_type'] == '4') {
        commonWidgets.add(
          InkWell(
            onTap: () {
              // 拼团
              if (item['results'][0]['ecactivity_classify'] == 1) {
                Map<String, dynamic> map = {
                  'icon_name': item['activity_num_name'],
                  'activity_num_id':item['activity_num_id'],
                  'pic_url': '',
                  'linktype': 9,
                  'linktarget': null,
                  'shop_id': item['results'][0]['ec_shop_num_id']
                };
                Get.toNamed(
                  RouteConfig.collage,
                  arguments: {'model': map},
                );
              } else if (item['results'][0]['ecactivity_classify'] == 2) {
                // 限时秒杀
                Map<String, dynamic> map = {'results': item['results']};
                Get.toNamed(
                  RouteConfig.seckillHome,
                  parameters: {},
                  arguments: {'model': map},
                );
              } else if (item['results'][0]['ecactivity_classify'] == 3) {
                // 预售
                Map<String, dynamic> map = {
                  'icon_name': item['activity_num_name'],
                  'pic_url': '',
                  'linktype': 12,
                  'linktarget': item['results'][0]['ecactivity_id'],
                  'shop_id': item['results'][0]['ec_shop_num_id'],
                };
                Get.toNamed(
                  RouteConfig.preSaleActive,
                  arguments: {'model': map},
                );
              } else {
                Map<String, dynamic> map = {
                  'icon_name': item['activity_num_name'],
                  'activity_num_id':item['activity_num_id'],
                  'pic_url': '',
                  'linktype': 9,
                  'linktarget': null
                };
                Get.toNamed(
                  RouteConfig.collage,
                  arguments: {'model': map},
                );
              }
            },
            child: Container(
              margin: EdgeInsets.only(bottom: 20.w),
              child: Stack(
                children: <Widget>[
                  item['results'].length != 0
                      ? new Image(
                          image: new NetworkImage(
                            item['activity_cover_url'],
                          ),
                        )
                      : Container(),
                  item['tag_name'] != null && item['results'].length != 0
                      ? Positioned(
                          //方法二
                          right: 20.w,
                          bottom: 20.w,
                          child: new Container(
                            padding: EdgeInsets.only(
                              left: 6.0,
                              right: 6.0,
                              top: 2.0,
                              bottom: 2.0,
                            ),
                            decoration: BoxDecoration(
                              border: Border.all(
                                width: 1,
                                color: Color(0xff708090),
                              ),
                              borderRadius: BorderRadius.all(
                                Radius.circular(30),
                              ),
                            ),
                            child: Text(
                              item['tag_name'],
                              style: TextStyle(
                                color: Color(0xff708090),
                                fontSize: 10,
                              ),
                            ),
                          ),
                        )
                      : Container(),
                ],
              ),
            ),
          ),
        );
      } else if (item['adv_type'] == '5') {
        var data = jsonDecode(item['coupon_num_name']);
        commonWidgets.add(
          Container(
            child: ListView.builder(
              physics: NeverScrollableScrollPhysics() ,
              shrinkWrap: true,
              itemExtent: 160.0,
              itemCount: data.length,
              itemBuilder: (ctx, index) {
                return InkWell(
                  onTap: data[index]['cover_url'] == null
                      ? () {}
                      : () {
                          toast('领取中...');
                          var params = {
                            "use_platform": 2,
                            "coupon_num_id":
                                data[index]['series'].toString(), //券编码
                            "usr_num_id": SpUtil.getInt('empeNumId'),
                            "access_token": SpUtil.getString('token'),
                            "relation": "领券中心",
                            "qsource": 301,
                            "relation_indate": "永久有效",
                            "user_num_id": SpUtil.getInt('empeNumId'),
                          };
                          Api.getCoupon(params).listen(
                            (event) {
                              toastDismissOther(event['message']);
                            },
                          );
                        },
                  child: Container(
                    constraints: new BoxConstraints.expand(
                      height: 134.0,
                    ),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(4.0),
                      image: DecorationImage(
                        image: NetworkImage("${data[index]['cover_url']}"),
                        fit: BoxFit.cover,
                      ),
                      color: Color(0xfff2c899),
                    ),
                    margin: EdgeInsets.only(bottom: 20.w, top: 20.w),
                    child: Row(
                      children: data[index]['cover_url'] != null
                          ? []
                          : [
                              Container(
                                width: 100.0,
                                margin: EdgeInsets.only(right: 20.w),
                                padding: EdgeInsets.only(left: 20.w),
                                child: Column(
                                  children: [
                                    Container(
                                      height: 30,
                                    ),
                                    data[index]['coupontype'] == '0'
                                        ? Row(
                                            children: [
                                              Text(
                                                '${data[index]['face_value'] / 10}',
                                                style: TextStyle(
                                                  color: Color(0xffa5673f),
                                                  fontSize: 36.0,
                                                ),
                                              ),
                                              Text(
                                                '折',
                                                style: TextStyle(
                                                  color: Color(0xffa5673f),
                                                ),
                                              ),
                                            ],
                                          )
                                        : Row(
                                            children: [
                                              Text(
                                                '¥',
                                                style: TextStyle(
                                                  color: Color(0xffa5673f),
                                                ),
                                              ),
                                              Text(
                                                '${data[index]['face_value']}',
                                                style: TextStyle(
                                                  color: Color(0xffa5673f),
                                                  fontSize: 36.0,
                                                ),
                                              ),
                                            ],
                                          ),
                                    Container(
                                      margin: EdgeInsets.only(top: 4.0),
                                      child: _couponType(
                                          data[index]['coupontype']),
                                    ),
                                  ],
                                ),
                              ),
                              Expanded(
                                child: Stack(
                                  children: [
                                    item['tag_name'] != null
                                        ? Positioned(
                                            //方法二
                                            right: 20.w,
                                            bottom: 20.w,
                                            child: new Container(
                                              padding: EdgeInsets.only(
                                                left: 6.0,
                                                right: 6.0,
                                                top: 2.0,
                                                bottom: 2.0,
                                              ),
                                              decoration: BoxDecoration(
                                                border: Border.all(
                                                  width: 1,
                                                  color: Color(0xff708090),
                                                ),
                                                borderRadius: BorderRadius.all(
                                                  Radius.circular(10),
                                                ),
                                              ),
                                              child: Text(
                                                item['tag_name'],
                                                style: TextStyle(
                                                  color: Color(0xff708090),
                                                  fontSize: 10,
                                                ),
                                              ),
                                            ),
                                          )
                                        : Container(),
                                    Container(
                                      // width: 400.w,
                                      child: Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.start,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Container(
                                            margin:
                                                EdgeInsets.only(bottom: 10.0),
                                            padding: EdgeInsets.only(top: 18.w),
                                            child: Text(
                                              data[index]['title'],
                                              style: TextStyle(
                                                color: Color(0xff000000),
                                                fontSize: 18.0,
                                              ),
                                            ),
                                          ),
                                          Container(
                                            child: item['start_time'] != null &&
                                                    item['end_time'] != null
                                                ? _getDate(item['start_time'],
                                                    item['end_time'])
                                                : Container(),
                                          ),
                                          InkWell(
                                            onTap: () {
                                              toast('领取中...');
                                              var params = {
                                                "use_platform": 2,
                                                "coupon_num_id": data[index]
                                                        ['series']
                                                    .toString(), //券编码
                                                "usr_num_id":
                                                    SpUtil.getInt('empeNumId'),
                                                "access_token":
                                                    SpUtil.getString('token'),
                                                "relation": "领券中心",
                                                "qsource": 301,
                                                "relation_indate": "永久有效",
                                                "user_num_id":
                                                    SpUtil.getInt('empeNumId'),
                                              };
                                              Api.getCoupon(params).listen(
                                                (event) {
                                                  toastDismissOther(
                                                      event['message']);
                                                },
                                              );
                                            },
                                            child: Container(
                                              padding: EdgeInsets.only(
                                                left: 10.0,
                                                right: 10.0,
                                                top: 4.0,
                                                bottom: 8.0,
                                              ),
                                              margin:
                                                  EdgeInsets.only(bottom: 20.w),
                                              decoration: BoxDecoration(
                                                color: Color(0xffa5673f),
                                                borderRadius:
                                                    BorderRadius.circular(20.0),
                                              ),
                                              child: Text(
                                                '立即领取',
                                                style: TextStyle(
                                                  color: Color(0xffffffff),
                                                  fontSize: 16,
                                                ),
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                    ),
                  ),
                );
              },
            ),
          ),
        );
      }
    }
    return commonWidgets;
  }

  Widget _getDate(start, end) {
    var startTime = start.split(" ")[0];
    var endTime = end.split(" ")[0];
    return Container(
      // width: 300.w,
      margin: EdgeInsets.only(bottom: 10.0),
      child: Text(
        '有效期 $startTime -- $endTime',
        style: TextStyle(
          color: Color(0xff333333),
        ),
      ),
    );
  }

  /// 搜索无结果widget
  Widget _searchResultAndRecommendCommodityList() {
    return Container(
      child: SingleChildScrollView(
        child: Container(
          child: Column(
            children: [
              Container(
                width: double.infinity,
                color: Colors.white,
                padding: EdgeInsets.symmetric(vertical: 40),
                child: Column(
                  children: [
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 30),
                      child: Text(
                        "抱歉，没有找到\"${logic.state.searchTextEditingController.text}\"相关店铺",
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: Colors.red,
                          fontWeight: FontWeight.bold,
                          fontSize: 18,
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.only(top: 20),
                      child: Text(
                        "换个词试试吧",
                        style: TextStyle(color: Colors.red, fontSize: 16),
                      ),
                    ),
                  ],
                ),
              ),
              // 广告
              state.advertising.length > 0
                  ? Column(
                      children: _newList(state.advertising),
                    )
                  : Text(''),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 30, vertical: 20),
                child: Row(
                  children: [
                    Expanded(
                      child: Container(
                        height: 1,
                        color: Colors.grey,
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 20),
                      child: Text(
                        "猜您喜欢",
                        style: TextStyle(
                            fontSize: 16, fontWeight: FontWeight.bold),
                      ),
                    ),
                    Expanded(
                      child: Container(
                        height: 1,
                        color: Colors.grey,
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                child: StaggeredGridView.countBuilder(
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  padding: EdgeInsets.symmetric(horizontal: setWidth(26)),
                  crossAxisCount: 4,
                  itemCount: state.recommendCommodityList.length,
                  itemBuilder: (BuildContext context, int index) {
                    return _buildRecommendCommodityItemWidget(
                        state.recommendCommodityList[index]);
                  },
                  staggeredTileBuilder: (index) => StaggeredTile.fit(2),
                  mainAxisSpacing: setWidth(20), // 排间距
                  crossAxisSpacing: setWidth(18), // 列间距
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildRecommendCommodityItemWidget(Map commodity) {
    String imgUrl = commodity['image_default_id'];
    String goodsName = commodity['title'];
    String price1 = commodity['price'].toString();
    String price2 = commodity['mkt_price'].toString();
    bool soldOutBool = commodity['style_store'] <= 0;

    return InkWell(
      child: Container(
        color: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 5),
        child: Column(
          children: [
            Container(
              // child: Image.network(imgUrl)
              child: Stack(
                children: [
                  cacheImage(
                    imageUrl: imgUrl,
                  ),
                  Positioned(
                    left: setWidth(110),
                    top: setWidth(100),
                    child: soldOutBool
                        ? Container(
                            width: setWidth(120),
                            height: setWidth(120),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              color: Color(0xffbbbbbb).withOpacity(0.7),
                              borderRadius: BorderRadius.circular(setWidth(60)),
                            ),
                            child: Text(
                              '售罄',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 15,
                              ),
                            ),
                          )
                        : SizedBox(),
                  ),
                ],
              ),
            ),
            Container(
              alignment: Alignment.topLeft,
              padding: const EdgeInsets.only(top: 10),
              child: Text(
                goodsName,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    fontSize: 14,
                    color: Colors.black,
                    fontWeight: FontWeight.bold),
              ),
            ),
            Container(
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(
                    child: Row(
                      children: [
                        Container(
                          padding: const EdgeInsets.only(right: 8.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              RichText(
                                  text: TextSpan(children: [
                                TextSpan(
                                    text: '¥',
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: Config.mainColor,
                                    )),
                                TextSpan(
                                    text: price1,
                                    style: TextStyle(
                                      fontSize: 14,
                                      fontWeight: FontWeight.bold,
                                      color: Config.mainColor,
                                    )),
                              ])),
                            ],
                          ),
                        ),
                        Container(
                          child: Text(
                            "￥$price2",
                            style: TextStyle(
                              fontSize: 12,
                              color: const Color(0xFFCCCCCC),
                              decoration: TextDecoration.lineThrough,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  if (commodity['fresh_type'] != 8)
                    Container(
                      child: IconButton(
                        icon: Image.asset(
                          'assets/images/add_shopping_cart.png',
                          width: 20,
                          color: !soldOutBool
                              ? Color(0xffEA5504)
                              : Color(0xffcccccc),
                          height: 20,
                        ),
                        iconSize: 30,
                        onPressed: () {
                          if (!soldOutBool) {
                            // String ecShopNumId =
                            //     SpUtil.getInt('storeShopNum')?.toString();
                            String ecShopNumId =
                                commodity['shop_num_id']?.toString() ??
                                    SpUtil.getObject(
                                            Config.GET_SHOP_INFO)['shop_id']
                                        ?.toString();
                            String itemNumId =
                                commodity['default_item_num_id']?.toString();
                            String styleNumId =
                                commodity['style_num_id']?.toString();
                            String ecStyleNumId =
                                commodity['ec_style_num_id']?.toString();
                            logic.requestAddGoods(ecShopNumId, itemNumId,
                                styleNumId, ecStyleNumId);
                          }
                        },
                      ),
                    )
                ],
              ),
            ),
          ],
        ),
      ),
      onTap: () {
        Get.toNamed(RouteConfig.goodsDetail, arguments: {
          'itemNumId': commodity["default_item_num_id"].toString(),
          'styleNumId': commodity["style_num_id"].toString(),
          'shopId': commodity["shop_num_id"].toString(),
          'typeIndex': commodity['is_pre_sale'] ?? 0,
        });
      },
    );
  }
}
